import 'dart:async';

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sptapp/config/const.dart';

class BarChartSample5 extends StatefulWidget {
  final List datas;
  final List values;
  final List? bottomValues;
  final int selType;
  final int selIndex;
  final String unit;
  final bool isRef;
  const BarChartSample5({super.key, required this.datas, required this.values, required this.selType, required this.selIndex, required this.unit, this.bottomValues, required this.isRef,});

  @override
  State<StatefulWidget> createState() => BarChartSample5State();
}

class BarChartSample5State extends State<BarChartSample5> {
  double barWidth = 22;
  double bSpace = 1;
  Color mainLineColor = Color.fromRGBO(255, 255, 255, 0);

  List<BarChartGroupData> _spots = [];


  double maxValue = 0;
  double minValue = 0;
  double aavgValue = 0;
  double bavgValue = 0;

  int touchedGroupIndex = -1;
  int showIndex = -1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getSpots();
  }

  getSpots(){
    print('getSpots ==');
    maxValue = 0;
    minValue = 0;
    aavgValue = 0;
    bavgValue = 0;
    _spots.clear();
    if(widget.datas.isEmpty){
      return;
    }
    if(widget.datas.isNotEmpty){
      bSpace = widget.datas.length / 4;
    }
    for(int i=0; i<widget.datas.length; i++ ){
      if(i > widget.values.length-1){
        _spots.add(
          BarChartGroupData(
            x: i,
            barRods: [
              BarChartRodData(
                toY: 0,
              )
            ],
            showingTooltipIndicators: [],
          ),
        );
      }else {
        LinearGradient linearGradient = LinearGradient(
          colors: [
            themeColor,
            themeColor,
          ],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        );

        if(widget.selType == 1){
          linearGradient = LinearGradient(
            colors: [
              Color.fromRGBO(0, 255, 1, 1),
              Color.fromRGBO(0, 153, 1, 1),
            ],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          );
        }else if(widget.selType == 2){
          linearGradient = LinearGradient(
            colors: [
              Color(0xffcc9d07),
              Color(0xffcc9d07),
            ],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          );
        }

        LinearGradient blinearGradient = LinearGradient(
          colors: [
            Color(0xffcc9d07),
            Color(0xffcc9d07),
          ],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        );

        if(widget.bottomValues!=null && widget.bottomValues!.isNotEmpty){
          _spots.add(
            BarChartGroupData(
              x: i,
              barRods: [
                BarChartRodData(
                    toY: double.parse(widget.values[i].toString()),
                    gradient: linearGradient,
                    borderRadius: BorderRadius.circular(4.w)
                ),
                BarChartRodData(
                    toY: double.parse(widget.bottomValues![i].toString()),
                    gradient: blinearGradient,
                    borderRadius: BorderRadius.circular(4.w)
                )
              ],
              groupVertically:true,
              showingTooltipIndicators: touchedGroupIndex == i ? [showIndex]:[],
            ),
          );
        }else{
          _spots.add(
            BarChartGroupData(
              x: i,
              barRods: [
                BarChartRodData(
                    toY: double.parse(widget.values[i].toString()),
                    gradient: linearGradient,
                    borderRadius: BorderRadius.circular(4.w)
                ),
              ],
              groupVertically:true,
              showingTooltipIndicators: touchedGroupIndex == i ? [showIndex]:[],
            ),
          );
        }
       
        if(double.parse(widget.values[i].toString()) > maxValue){
          maxValue = double.parse(widget.values[i].toString());
        }

        if(double.parse(widget.values[i].toString()) < minValue){
          minValue = double.parse(widget.values[i].toString());
        }
        if(widget.bottomValues!=null && widget.bottomValues!.isNotEmpty){
          if(double.parse(widget.bottomValues![i].toString()) < minValue){
            minValue = double.parse(widget.bottomValues![i].toString());
          }
        }
      }
    }

    if(widget.selType == 0 || widget.selType == 4){
      // if(maxValue.abs() > minValue.abs()){
      //   minValue  = -maxValue.abs();
      // }else if(maxValue.abs() < minValue.abs()){
      //   maxValue = minValue.abs();
      // }
    }else if(widget.selType == 1){
      maxValue = 100;
      minValue = 0;
    }else{
      minValue = 0;
    }

    aavgValue = maxValue/2;
    bavgValue = minValue/2;
    if(mounted){
      setState(() {});
    }
  }

  _hideTool(){
    Future.delayed(Duration(seconds: 3),(){
      touchedGroupIndex = -1;
      showIndex = -1;
      getSpots();
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  void didUpdateWidget(covariant BarChartSample5 oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    if(widget.values != oldWidget.values){
    //   maxValue = 0;
    //   minValue = 0;
    //   aavgValue = 0;
    //   bavgValue = 0;
      print('widget======${widget.values}   ');
      print('oldWidget======${oldWidget.values}   ');
      getSpots();
    }
  }

  Widget bottomTitleWidgets(double value, TitleMeta meta) {
    if(widget.datas.isEmpty){
      return Container();
    }
    if(widget.selIndex == 3){
      print('inex == ${widget.datas[value.toInt()].toString()}');
        int index =  0;
        String month = '';
        if(index == 1){
          month = 'Jan';
        }else if(index == 2){
          month = 'Feb';
        }else if(index == 3){
          month = 'Mar';
        }else if(index == 4){
          month = 'Apr';
        }else if(index == 5){
          month = 'May';
        }else if(index == 6){
          month = 'Jun';
        }else if(index == 7){
          month = 'Jul';
        }else if(index == 8){
          month = 'Aug';
        }else if(index == 9){
          month = 'Sep';
        }else if(index == 10){
          month = 'Oct';
        }else if(index == 11){
          month = 'Nov';
        }else if(index == 12){
          month = 'Dec';
        }
      return SideTitleWidget(
        axisSide: meta.axisSide,
        space: 12,
        angle: 0,
        child: Text(
          '${widget.datas[value.toInt()].toString()}',
          style: TextStyle(
            fontSize: 22.sp,
            color: Color.fromRGBO(255, 255, 255, 0.3),
            fontWeight: FontWeight.bold,
          ),
        ),
      );
    }
    int length = widget.datas.length ~/ 4;
    if(value.toInt() == length || value.toInt() == length *2 || value.toInt() == length *3){
      return SideTitleWidget(
        axisSide: meta.axisSide,
        space: 12,
        angle: 0,
        child: Text(
          widget.datas.isNotEmpty? widget.datas[value.toInt()].toString():'',
          style: const TextStyle(
            fontSize: 12,
            color: Color.fromRGBO(255, 255, 255, 0.3),
            fontWeight: FontWeight.bold,
          ),
        ),
      );
    }
    return Container();
  }

  @override
  Widget build(BuildContext context) {

    final ExtraLinesData extraLinesData;
    print('maxvalue==== $maxValue');
    if(widget.selType ==0 || widget.selType == 4){
      extraLinesData = ExtraLinesData(
          horizontalLines: [
            HorizontalLine(
                y: 0,
                color: Color.fromRGBO(255, 255, 255, 0.3),
                strokeWidth: 1,
                label: HorizontalLineLabel(
                  show: true,
                  alignment: Alignment.topRight,
                  padding: const EdgeInsets.only(right: 5, bottom: 5),
                  style:  TextStyle(
                      fontSize: 20.sp,
                      fontWeight: FontWeight.w400,
                      color: Color.fromRGBO(255, 255, 255, 0.5)
                  ),
                  labelResolver: (line) => '0 ${widget.unit}',
                ),
                dashArray: [2,2]
            ),
            HorizontalLine(
              y: maxValue,
              label: HorizontalLineLabel(
                show: true,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '$maxValue ${widget.unit}',
              ),
              color: Color.fromRGBO(255, 255, 255, 0.3),
              strokeWidth: 0.5,
            ),
            HorizontalLine(
              y: maxValue/2,
              label: HorizontalLineLabel(
                show: true,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '',
              ),
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 0.5,
            ),
            HorizontalLine(
              y: minValue/2,
              label: HorizontalLineLabel(
                show: true,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '',
              ),
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 0.5,
            ),
            HorizontalLine(
              y: minValue,
              label: HorizontalLineLabel(
                show: true,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '${minValue.toString().replaceAll("-", "")} ${widget.unit}',
              ),
              color: Color.fromRGBO(255, 255, 255, 0.3),
              strokeWidth: 0.5,
            ),
          ],
          verticalLines: [
            VerticalLine(
              x: 0.5,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
            VerticalLine(
              x: widget.datas.length /4 * 2,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
            VerticalLine(
              x: widget.datas.length /4 * 3,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
          ]
      );
    }
    else if(widget.selType == 1){
      extraLinesData = ExtraLinesData(
          horizontalLines: [
            HorizontalLine(
              y: maxValue,
              label: HorizontalLineLabel(
                show: true,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '$maxValue ${widget.unit}',
              ),
              color: Color.fromRGBO(255, 255, 255, 0.3),
              strokeWidth: 0.5,
            ),
            HorizontalLine(
              y: 75,
              label: HorizontalLineLabel(
                show: true,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '',
              ),
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 0.1,
            ),
            HorizontalLine(
                y: 50,
                label: HorizontalLineLabel(
                  show: true,
                  alignment: Alignment.topRight,
                  padding: const EdgeInsets.only(right: 5, bottom: 5),
                  style:  TextStyle(
                      fontSize: 20.sp,
                      fontWeight: FontWeight.w400,
                      color: Color.fromRGBO(255, 255, 255, 0.5)
                  ),
                  labelResolver: (line) => '50 ${widget.unit}',
                ),
                color: Color.fromRGBO(255, 255, 255, 0.3),
                strokeWidth: 0.5,
                dashArray: [2,2]
            ),
            HorizontalLine(
              y: 25,
              label: HorizontalLineLabel(
                show: true,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.1)
                ),
                labelResolver: (line) => '',
              ),
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 0.1,
            ),
            HorizontalLine(
              y: minValue,
              label: HorizontalLineLabel(
                show: true,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '$minValue ${widget.unit}',
              ),
              color: Color.fromRGBO(255, 255, 255, 0.3),
              strokeWidth: 0.5,
            ),
          ],
          verticalLines: [
            VerticalLine(
              x: widget.datas.length /4,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
            VerticalLine(
              x: widget.datas.length /4 * 2,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
            VerticalLine(
              x: widget.datas.length /4 * 3,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
          ]
      );
    }else{
      extraLinesData = ExtraLinesData(
          horizontalLines: [
            HorizontalLine(
              y: maxValue,
              label: HorizontalLineLabel(
                show: true,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '$maxValue ${widget.unit}',
              ),
              color: Color.fromRGBO(255, 255, 255, 0.3),
              strokeWidth: 0.5,
            ),
            HorizontalLine(
              y: maxValue/4*3,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 0.1,
              label: HorizontalLineLabel(
                show: false,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '',
              ),

            ),
            HorizontalLine(
                y: aavgValue,
                color: Color.fromRGBO(255, 255, 255, 0.3),
                strokeWidth: 1,
                label: HorizontalLineLabel(
                  show: true,
                  alignment: Alignment.topRight,
                  padding: const EdgeInsets.only(right: 5, bottom: 5),
                  style:  TextStyle(
                      fontSize: 20.sp,
                      fontWeight: FontWeight.w400,
                      color: Color.fromRGBO(255, 255, 255, 0.5)
                  ),
                  labelResolver: (line) => '${aavgValue.toString().replaceAll("-", "")} ${widget.unit}',
                ),
                dashArray: [2,2]
            ),
            HorizontalLine(
              y: maxValue/4,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 0.1,
              label: HorizontalLineLabel(
                show: false,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '',
              ),

            ),
            HorizontalLine(
              y: minValue,
              label: HorizontalLineLabel(
                show: true,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '$minValue ${widget.unit}',
              ),
              color: Color.fromRGBO(255, 255, 255, 0.3),
              strokeWidth: 0.5,
            ),
          ],
          verticalLines: maxValue != 0? [
            VerticalLine(
              x: widget.datas.length /4,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
            VerticalLine(
              x: widget.datas.length /4 * 2,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
            VerticalLine(
              x: widget.datas.length /4 * 3,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
          ]:[]
      );
    }

    return AspectRatio(
      aspectRatio: 1,
      child: Padding(
        padding: EdgeInsets.only(
          left: 0,
          right: 0,
          top: 20,
          bottom: 0,
        ),
        child: BarChart(
          BarChartData(
            alignment: BarChartAlignment.spaceEvenly,
            maxY: maxValue,
            minY: minValue,
            // groupsSpace: bSpace,
            barTouchData: BarTouchData(
              handleBuiltInTouches: false,
              enabled: true,
              longPressDuration: Duration.zero,
              touchCallback: (FlTouchEvent event, barTouchResponse) {
                if (!event.isInterestedForInteractions ||
                    barTouchResponse == null ||
                    barTouchResponse.spot == null) {
                  return;
                }

                final rodIndex = barTouchResponse.spot!.touchedBarGroupIndex;
                final tipIndex = barTouchResponse.spot!.touchedRodDataIndex;
                 touchedGroupIndex = rodIndex;
                 showIndex = tipIndex;
                getSpots();
                _hideTool();
              },
              touchTooltipData: BarTouchTooltipData(
                getTooltipColor: (touchedSpot) => Color(0xff141414),
                fitInsideHorizontally: true,
                fitInsideVertically: true,
                getTooltipItem: ( BarChartGroupData group,
                    int groupIndex,
                    BarChartRodData rod,
                    int rodIndex,) {
                  final textStyle = TextStyle(
                    color: Color.fromRGBO(255, 255, 255, 0.5),
                    fontWeight: FontWeight.bold,
                    fontSize: 18.sp,
                  );
                  return BarTooltipItem(
                    '',
                    TextStyle(
                      color: Color.fromRGBO(255, 255, 255, 0.5),
                      fontWeight: FontWeight.bold,
                      fontSize: 18.sp,
                    ),
                    children: [
                      TextSpan(
                          text: '${widget.datas[group.x]}\n',
                          style: TextStyle(
                            color: Color.fromRGBO(255, 255, 255, 0.5),
                            fontWeight: FontWeight.bold,
                            fontSize: 20.sp,
                          )
                      ),
                      TextSpan(
                          text: '${rod.toY.toString().replaceAll("-", "")}',
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 20.sp,
                          )
                      ),
                    ],
                    textAlign: TextAlign.left
                  );
                },
              ),
            ),
            titlesData: FlTitlesData(
              show: true,
              topTitles: const AxisTitles(
                sideTitles: SideTitles(
                  showTitles: false,
                ),
              ),
              bottomTitles: AxisTitles(
                sideTitles: SideTitles(
                  showTitles: true,
                  reservedSize: 26,
                  interval: bSpace,
                  maxIncluded: false,
                  minIncluded: false,
                  getTitlesWidget: bottomTitleWidgets,
                ),

              ),
              leftTitles: const AxisTitles(
                sideTitles: SideTitles(
                  showTitles: false,
                ),
              ),
              rightTitles: const AxisTitles(
                sideTitles: SideTitles(
                  showTitles: false,
                ),
              ),
            ),
            gridData: FlGridData(
                show: true,
                drawVerticalLine: false,
                drawHorizontalLine: false,
            ),
            borderData: FlBorderData(
              show: false,
            ),
            extraLinesData: extraLinesData,
            barGroups: _spots,
          ),
        ),
      ),
    );
  }
}